﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Data;
using System.Collections;
using System.Reflection;
using RTUDataAcquisition.AppCode;

namespace RTUDataAcquisition.DataAccess
{
    public abstract class DbHelper
    {
        public DbHelper()
        {
        }

        /// <summary>
        /// 数据库连接测试
        /// </summary>
        /// <param name="strConn">数据库连接字符串</param>
        /// <returns></returns>
        public static bool ConnectionTest(string strConn)
        {
            using (SqlConnection connection = new SqlConnection(strConn))
            {
                bool isOK = false;
                try
                {
                    connection.Open();
                    isOK = true;
                }
                catch(Exception ex)
                {
                    Messages.SaveLog(ex);
                    connection.Close();
                    isOK = false;
                }
                finally
                {
                    connection.Close();
                }
                return isOK;
            }
        }

        /// <summary>
        /// 批量导入数据
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="strDBTableName">数据库表名</param>
        /// <param name="strConn">数据库连接字符串</param>
        public static void BulkToDB(DataTable dt, string strDBTableName, string strConn)
        {
            using (SqlConnection sqlConn = new SqlConnection(strConn))
            {
                SqlBulkCopy bulkCopy = new SqlBulkCopy(strConn, SqlBulkCopyOptions.FireTriggers);
                //SqlBulkCopy bulkCopy = new SqlBulkCopy(strConn);
                bulkCopy.DestinationTableName = strDBTableName;
                bulkCopy.BatchSize = dt.Rows.Count;

                try
                {
                    sqlConn.Open();
                    if (dt != null && dt.Rows.Count != 0)
                    {
                        bulkCopy.WriteToServer(dt);
                    }
                }
                catch (Exception ex)
                {
                    //Messages.SaveLog(ex, ELogLayer.DB);
                    throw ex;
                }
                finally
                {
                    sqlConn.Close();
                    if (bulkCopy != null)
                    {
                        bulkCopy.Close();
                    }
                }
            }
        }


        #region 公用方法
        /// <summary>
        /// 是否存在1 
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static bool Exists(string strSql, string conStr)
        {
            object obj = GetSingle(strSql, conStr);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region  执行简单SQL语句

        /// <summary>1
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string conStr)
        {
            using (SqlConnection connection = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
        }

        /// <summary>1
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString, string conStr)
        {
            using (SqlConnection connection = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, string conStr)
        {
            using (SqlConnection connection = new SqlConnection(conStr))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                    connection.Close();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    connection.Close();
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
                return ds;
            }
        }
        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string conStr, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 执行新增SQL语句，返回新增的ID
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>返回新增的ID</returns>
        public static int ExecuteAdd(string SQLString, string conStr, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        if (rows > 0)
                        {
                            cmd.CommandText = "SELECT @@IDENTITY AS id";
                            cmd.ExecuteNonQuery();
                            return Convert.ToInt32(cmd.ExecuteScalar());
                        }
                        else
                        {
                            return 0;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
        }

        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null || parameter.Value.ToString().Trim() == ""))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 数据库名称查询

        /// <summary>
        /// 获得所有数据库名称
        /// </summary>
        /// <returns></returns>
        public static ArrayList getAllDataBase(string conStr)
        {
            SqlConnection connection = null;
            ArrayList DBNameList = new ArrayList();
            try
            {
                connection = new SqlConnection(conStr);
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }
                DataTable DBNameTable = new DataTable();
                SqlDataAdapter Adapter = new SqlDataAdapter("select name from master..sysdatabases", connection);
                lock (Adapter)
                {
                    Adapter.Fill(DBNameTable);
                }
                foreach (DataRow row in DBNameTable.Rows)
                {
                    DBNameList.Add(row["name"]);
                }
                connection.Close();
                return DBNameList;
            }
            catch (Exception)
            {
                connection.Close();
                return null;
            }
        }
        #endregion
    }
}
